import os
import platform
import shutil
import subprocess

from PIL import Image

from common import get_base_dir


def create_base_image():
    image = Image.open(os.path.join(get_base_dir(), "res", "app_icon.png"))
    return image


def get_build_dir():
    build_dir = os.path.join(get_base_dir(), "build")
    if not os.path.exists(build_dir):
        os.makedirs(build_dir)
    return build_dir


def create_windows_ico(image):
    """为 Windows 创建 .ico 格式图标"""
    try:
        # Windows 图标尺寸
        sizes = [16, 24, 32, 48, 64, 128, 256]
        icon_images = []

        # 创建不同尺寸的图标
        for size in sizes:
            icon_images.append(image.resize((size, size), Image.Resampling.LANCZOS))

        # 保存为 .ico 文件
        icon_path = os.path.join(get_build_dir(), "app.ico")
        icon_images[0].save(
            icon_path,
            format="ICO",
            sizes=[(s, s) for s in sizes],
            append_images=icon_images[1:],
        )
        print("成功生成 Windows 图标文件: app.ico")
        return True
    except Exception as e:
        print(f"创建 Windows 图标时出错: {str(e)}")
        return False


def create_macos_icns(image):
    """为 macOS 创建 .icns 格式图标"""
    try:
        # 创建临时目录
        iconset_path = os.path.join(get_build_dir(), "icons.iconset")
        if os.path.exists(iconset_path):
            shutil.rmtree(iconset_path)
        os.makedirs(iconset_path)

        # 创建不同尺寸的图标
        icon_sizes = [16, 32, 64, 128, 256, 512, 1024]
        for s in icon_sizes:
            img = image.resize((s, s), Image.Resampling.LANCZOS)
            img.save(os.path.join(iconset_path, f"icon_{s}x{s}.png"))
            if s <= 512:  # 创建 @2x 版本
                img = image.resize((s * 2, s * 2), Image.Resampling.LANCZOS)
                img.save(os.path.join(iconset_path, f"icon_{s}x{s}@2x.png"))

        print("生成 macOS 图标文件...")
        # 使用 iconutil 转换为 icns
        result = subprocess.run(
            ["iconutil", "-c", "icns", iconset_path], capture_output=True, text=True
        )

        if result.returncode != 0:
            print(f"转换失败: {result.stderr}")
            return False

        # 重命名生成的文件
        if os.path.exists(os.path.join(get_build_dir(), "icons.icns")):
            if os.path.exists(os.path.join(get_build_dir(), "app.icns")):
                os.remove(os.path.join(get_build_dir(), "app.icns"))
            os.rename(
                os.path.join(get_build_dir(), "icons.icns"),
                os.path.join(get_build_dir(), "app.icns"),
            )
            print("成功生成 macOS 图标文件: app.icns")

        # 清理临时文件
        shutil.rmtree(iconset_path)
        return True
    except Exception as e:
        print(f"创建 macOS 图标时出错: {str(e)}")
        if os.path.exists(iconset_path):
            shutil.rmtree(iconset_path)
        return False


def create_icon():
    """根据操作系统创建对应格式的图标"""
    try:
        # 创建基础图像
        base_image = create_base_image()

        # 根据操作系统创建对应格式的图标
        system = platform.system()
        if system == "Windows":
            return create_windows_ico(base_image)
        elif system == "Darwin":
            return create_macos_icns(base_image)
        else:
            print(f"不支持的操作系统: {system}")
            return False

    except Exception as e:
        print(f"创建图标时出错: {str(e)}")
        return False


if __name__ == "__main__":
    create_icon()
